package com.apo1o.cmscore.service.impl;

import com.apo1o.cmscore.bean.Category;
import com.apo1o.cmscore.bean.ext.CategoryExtend;
import com.apo1o.cmscore.dao.CategoryDao;
import com.apo1o.cmscore.exception.ServiceException;
import com.apo1o.cmscore.service.ICategoryService;
import com.apo1o.cmscore.util.ResultCode;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Apo1o
 * @since 2023-11-15
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements ICategoryService {
    @Autowired
    private CategoryDao categoryDao;



    //分页+条件查询(根据parent_id)
    @Override
    public IPage<Category> query(Integer pageNum, Integer pageSize, Integer parentId) {
        //1.参数判断
        if (pageNum == null || pageNum <= 0 || pageSize == null || pageSize <= 0)
            throw new ServiceException(ResultCode.PARAM_IS_INVALID);

        //2.分页查询 设置排序次序
        //  select * from cms_category where deleted = 0 and parent_id = ? order by parent_id, order_num;
        IPage<Category> p = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(parentId != null, Category::getParentId, parentId);
        qw.orderByAsc(Category::getParentId)
                .orderByAsc(Category::getOrderNum);
        categoryDao.selectPage(p, qw);

//        if (p.getTotal() == 0)
//            throw new ServiceException(ResultCode.CATEGORY_NOT_EXIST);

        return p;
    }

    //查询得到所有的一级栏目（含二级）
    @Override
    public List<CategoryExtend> queryAllParent() {
        List<CategoryExtend> list = categoryDao.queryAllWithCates();
        if (list == null || list.size() == 0)
            throw new ServiceException(ResultCode.CATEGORY_NOT_EXIST);

        return list;
    }
    //查询得到所有的一级栏目, 不含二级栏目
    @Override
    public List<Category> queryAllOneLevel() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(Category::getParentId);
        List<Category> list = categoryDao.selectList(queryWrapper);
        if (list == null || list.size() == 0)
            throw new ServiceException(ResultCode.CATEGORY_NOT_EXIST);
        return list;
    }

    @Override
    public List<Category> queryAll() {

        return categoryDao.selectList(null);
    }


}
